package org.chen;

import org.chen.pool.JedisConnect;

public class HyperloglogsJedisTest {
  public static void main(String[] args) {
    JedisConnect connect = new JedisConnect();
    connect.execute(jedis -> {
      jedis.flushDB();

      //Hyperloglogs是基于基数统计的算法，所以存储的元素不会重复
      // Hyperloglogs用于允许容错的统计，如网站浏览量统计等
      //Hyperloglogs的优势是占用的内存是固定的，内存消耗小

      //存
      jedis.pfadd("a1","a","b","c","d");

      //统计key中element的个数
      System.out.println(jedis.pfcount("a1"));//4

      jedis.pfadd("a2","c","d","e","f","g");

      //合并两个key中元素到新的key中，其实是将两个key的并集存到新的key中，可用作合并多个统计结果
      jedis.pfmerge("a3","a1","a2");
      System.out.println(jedis.pfcount("a3"));//7

      //Hyperloglogs官方给出的误差率是0.81%
      for (int i = 0; i < 1000; i++) {
        jedis.pfadd("uv","u"+i,"u"+(i+1));
        //按照理论，存入的数据会自动去重，所以应会存入1001个数据
      }
      System.out.println(jedis.pfcount("uv"));//994,有误差，但如果是统计uv这样可容错的统计，是可接受的
    });
  }
}
